package com.example.remindme

import android.app.AlertDialog
import android.app.DatePickerDialog
import android.content.res.Configuration
import android.os.Build
import android.os.Bundle
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.WindowManager
import android.widget.*
import androidx.annotation.RequiresApi
import androidx.appcompat.app.AppCompatActivity
import androidx.fragment.app.Fragment
import androidx.lifecycle.ViewModelProvider
import androidx.recyclerview.widget.RecyclerView
import com.example.remindme.RemindDatabase.ListEntity
import com.example.remindme.RemindDatabase.MatterEntity
import com.example.remindme.RemindModule.DataCard.Fragment.*
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch
import java.util.*

val Tag="lifecycle"
class RemindActivity : AppCompatActivity() {
    lateinit var landRecycler:RecyclerView
    @RequiresApi(Build.VERSION_CODES.M)
    lateinit var listbtn:Button
    lateinit var taskbtn:Button
     var cardFragment: ViewcardFragment?=null
    var taskFragment: taskFragment?=null
    // 新建两个变量

    override fun onConfigurationChanged(newConfig: Configuration) {
        Log.d(Tag, "onConfigurationChanged")
        super.onConfigurationChanged(newConfig)
    }

    override fun onAttachFragment(fragment: Fragment) {
        Log.d(Tag, "attachFragment")
        super.onAttachFragment(fragment)
    }


    override fun onCreate(savedInstanceState: Bundle?) {
       // 弹窗

        super.onCreate(savedInstanceState)
        Log.d(Tag, "mainActivity created")

        setContentView(R.layout.activity_remind)

        listbtn=findViewById(R.id.addlist)
        taskbtn=findViewById(R.id.addtask)


        if (savedInstanceState != null) {
            Log.d(Tag,"saveinstancestate")
            val temp= supportFragmentManager.findFragmentById(R.id.fragmentcontainer)
            val landTem=supportFragmentManager.findFragmentById(R.id.landFragmencontain)
            if(temp!=null&&temp is ViewcardFragment)  // 竖屏并且是处于 总结viewcard界面
            {
                cardFragment=temp as ViewcardFragment
                cardFragment!!.viewModel=ViewModelProvider(
                this,
                ViewModelProvider.AndroidViewModelFactory(this.application)
                )
                .get(ViewcardViewModel::class.java)
                supportFragmentManager.beginTransaction()
                    .replace(R.id.fragmentcontainer, cardFragment!!, "fragment")
                    .commit()
                Log.d(Tag, "mainActivity replace the fragment")
            }
            else if(temp!=null && temp is taskFragment)
            {
                Log.d(Tag,"find the straight task")
                taskFragment=temp
               taskFragment!!.viewModel =ViewModelProvider(
                    this,
                    ViewModelProvider.AndroidViewModelFactory(this.application)
                )
                    .get(TaskViewModel::class.java)
                supportFragmentManager.beginTransaction()
                    .addToBackStack(null)
                    .replace(R.id.fragmentcontainer, taskFragment!!, "taskfragment")
                    .commit()
            }
            if(landTem!=null &&landTem is taskFragment)
            {

                Log.d(Tag,"find the land task")
                taskFragment= landTem as taskFragment
                taskFragment!!.viewModel =ViewModelProvider(
                    this,
                    ViewModelProvider.AndroidViewModelFactory(this.application)
                )
                    .get(TaskViewModel::class.java)
                supportFragmentManager.beginTransaction()
                    .addToBackStack(null)
                    .replace(R.id.landFragmencontain, taskFragment!!, "taskfragment")
                    .commit()
            }


        }
        if (cardFragment == null) {
            cardFragment= ViewcardFragment()
            cardFragment!!.viewModel =ViewModelProvider(
                this,
                ViewModelProvider.AndroidViewModelFactory(this.application)
            )
                .get(ViewcardViewModel::class.java)
            supportFragmentManager.beginTransaction()
                .add(R.id.fragmentcontainer, cardFragment!!, "fragment")
                .commit()
            Log.d(Tag, "mainActivity add the fragment")
        }


        //如果没有，重新创建Fragment




         Log.d(Tag, "mainActivity create the card fragment")

       StartWork()
        initButton()

    }

    private fun initButton() {
        taskbtn.setOnClickListener {

            var isCalendar = false
            var isFalgged=0
            var timed=0L

            if(taskFragment==null)
            {


                Toast.makeText(this, "Sorry, please choose the list first!", Toast.LENGTH_SHORT).show()

            }
            else
            {
                val myDialog = AlertDialog.Builder(this).create()
                myDialog.show()
                val layout = LayoutInflater.from(this).inflate(R.layout.matter_dialog, null)
                val win = myDialog!!.window
                win!!.setContentView(layout)
                myDialog!!.window!!.clearFlags(WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM)
                val btnSure: Button = layout.findViewById(R.id.Matter_btnSure)
                val btnCancel: Button = layout.findViewById(R.id.Matter_btn_cancel)
                val imgBtn: ImageView = layout.findViewById(R.id.matter_img)
                val editMatter: EditText = layout.findViewById(R.id.matter_edit)
                val flag_tag:CheckBox=layout.findViewById(R.id.ifFlag)
                // 获取当前的时间
                val mcalendar = Calendar.getInstance();     //  获取当前时间    —   年、月、日
                val year = mcalendar.get(Calendar.YEAR);         //  得到当前年
                val month = mcalendar.get(Calendar.MONTH);       //  得到当前月
                val day = mcalendar.get(Calendar.DAY_OF_MONTH);
                btnCancel.setOnClickListener {
                    Toast.makeText(this, "Canceled!", Toast.LENGTH_SHORT).show()
                    myDialog.cancel()
                }
                btnSure.setOnClickListener {
                    val matterName = editMatter.text.toString()
                    //
                    myDialog.cancel()

                    val type= taskFragment!!.viewModel.listType.value as String
                    if(type== TYPE_ALL ||type== TYPE_FALGGED ||type== TYPE_TODAY ||type== TYPE_SCHEDULED)
                        Toast.makeText(this, "Sorry, please choose the list first!", Toast.LENGTH_SHORT).show()
                    else
                    {
                        val id=Calendar.getInstance().timeInMillis
                        if(isCalendar)
                        {
                            timed=mcalendar.timeInMillis

                        }
                        if(flag_tag.isChecked)
                            isFalgged=1
                        val matteEntity=MatterEntity(id,type,matterName,isFalgged,timed)
                        GlobalScope.launch {
                            taskFragment!!.viewModel.InsertRoom(matteEntity)
                            taskFragment!!.viewModel.queryRoomByType(type)
                        }
                        Toast.makeText(this, "A new Matter added successfully", Toast.LENGTH_SHORT).show()
                    }



                }

                imgBtn.setOnClickListener {
                    isCalendar = true

                    //  得到当前日
                    DatePickerDialog(this, object : DatePickerDialog.OnDateSetListener {      //  日期选择对话框
                        override fun onDateSet(view: DatePicker?, year: Int, month: Int, dayOfMonth: Int) {
                            mcalendar.set(Calendar.YEAR, year)
                            mcalendar.set(Calendar.MONTH, month)
                            mcalendar.set(Calendar.DAY_OF_MONTH, dayOfMonth)
                        }
                    }, year, month, day).show();


                }
            }

        }
            listbtn.setOnClickListener {
                // 必须在show后才能

                val myDialog = AlertDialog.Builder(this).create()
                myDialog.show()
                val layout = LayoutInflater.from(this).inflate(R.layout.listdialog, null)

                val win = myDialog!!.window
                win!!.setContentView(layout)
                val param = win.attributes
                // param.width=500
                win.attributes = param
                myDialog!!.window!!.clearFlags(WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM);
                val btnSure = layout.findViewById<Button>(R.id.btnSure)
                val editList: EditText = layout.findViewById(R.id.list_edit)
                btnSure.setOnClickListener {
                    val listName = editList.text.toString()

                    Toast.makeText(this, "Confirmed!", Toast.LENGTH_SHORT).show()
                    myDialog.cancel()
                    if (cardFragment != null) {
                        val id = cardFragment!!.viewModel.listNum as Int
                        GlobalScope.launch {
                            cardFragment!!.viewModel.addListType(ListEntity(id + 1, listName))
                            cardFragment!!.viewModel.requeryRoom()
                        }
                        Toast.makeText(this, "A new List added successfully", Toast.LENGTH_SHORT).show()

                    }

                }
                val btnCancel = layout.findViewById<Button>(R.id.btncancel)
                btnCancel.setOnClickListener {
                    Toast.makeText(this, "Canceled!", Toast.LENGTH_SHORT).show()
                    myDialog.cancel()
                }

            }
        }


    fun StartWork() {

        if (this.getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT) {

            // 实际上是当整个app 现在保存的type变了，就会自动的去查询
            cardFragment!!.viewModel.currentType.observe(this, {
                 taskFragment = loadTaskFragment()
                Log.d("search", "currentType Changed:$it")
                Log.d("search", "before Changed:${taskFragment!!.viewModel.listType.value}")

                // 这一步没有问题
                taskFragment!!.viewModel.listType.value = it.toString()
                //  taskFragment.addObserverMatters(it)
                // todo : no need the double observe, just straightly
                Log.d("search", "after Changed:${taskFragment!!.viewModel.listType.value}")
                supportFragmentManager.beginTransaction()
                    .addToBackStack(null)
                    .replace(R.id.fragmentcontainer, taskFragment!!, "taskfragment")
                    .commit()
            })//竖屏
        } else {
            //横屏
            cardFragment!!.viewModel.currentType.observe(this, {
                taskFragment = loadTaskFragment()
                taskFragment!!.viewModel.listType.value = it
                if (supportFragmentManager.findFragmentByTag("taskfragment") == null) {
                    supportFragmentManager.beginTransaction()
                        .add(R.id.landFragmencontain, taskFragment!!, "taskfragment")
                        .commit()
                } else {
                    supportFragmentManager.beginTransaction()
                        .replace(R.id.landFragmencontain, taskFragment!!, "taskfragment")
                        .commit()
                }
            })

        }

        // 对添加列表和添加任务设置鼠标点击事件

        // 弹出小窗


    }
    /*
    private fun showSingleButtonDialog(title: String, alertText: String, btnText: String, onClickListener:View.OnClickListener) {
        mDialog = builderForCustom!!.setTitle(title)
            .setMessage(alertText)
            .setSingleButton(btnText, onClickListener)
            .createSingleButtonDialog()
        mDialog!!.show()
    }

     */

    // 在主函数调用，在主函数完成鼠标点击事件

    override fun onDestroy() {
        Log.d(Tag, "mainActivity destroyed")
        super.onDestroy()
    }
    /*
       var popupWindow : PopupWindow? = null

    //一个自定义的布局，作为显示的内容
        private fun showPopupWindow( view: View){
            //初始化布局activity_popupwindow.xml
           val  contentView = getLayoutInflater().inflate(R.layout.choosedialog, null);
            //对布局里面的控件进行初始化并进行相应的操作



            //初始化PopupWindow
            popupWindow =  PopupWindow(contentView,
            WindowManager.LayoutParams.WRAP_CONTENT, WindowManager.LayoutParams.WRAP_CONTENT
            ,true);
            popupWindow.setTouchable(true);
            //设置好参数之后再show
            popupWindow.setBackgroundDrawable(BitmapDrawable());
            popupWindow.showAsDropDown(view);
        }



     */

    fun loadTaskFragment(): taskFragment {
        val  mytaskFragment= taskFragment()
        Log.d("life", " 我加载了个锤子")
        mytaskFragment.viewModel =ViewModelProvider(
            this,
            ViewModelProvider.AndroidViewModelFactory(this.application)
        )
            .get(TaskViewModel::class.java)



        return mytaskFragment
    }
}